<?php

namespace app\common\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Cache;
use think\Log;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Ecs\Ecs;

/**
* 
*/
class Orders extends Command
{
    static $acsClient = null;
    public  function randomstring($length = 8) {
        $str = 'abcdefghijkmnopqrstuvwxyz0123456789';
        for ($i = 0, $passwd = ''; $i < $length; $i++)
            $passwd .= substr($str, mt_rand(0, strlen($str) - 1), 1);

        return $passwd;
    }

	protected function configure()
    {
        $this->setName('orders')->setDescription('支付订单');
    }
    /**
    	 * 批量推送 先找status=0的notice 再找status=0的notice_user
    	 */	
    protected function execute(Input $Input,Output $output)
    {
        
        // $res = $this->sendSms('13347890121','SMS_173471929',['pro'=>'111','code'=>'222']);
        // var_dump($res);die();
        $token = $this->getToken();
        $start_time = time()-60;
        $end_time = time();

        $res = $this->getOrderList('all',date('Y-m-d H:i:s',$start_time),date('Y-m-d H:i:s',$end_time));
        if($res = json_decode($res,true)) {
            // var_dump($res);exit;
            $orders = $res['result']['orders'];
            if($orders) {
                foreach ($orders as $key => $value) {
                    // var_dump($value['status']);exit;
                    $order_id = $value['order_id'];
                    if($value['status']<20 || Db('wdcode')->where(['order_id'=>$order_id])->find()) {
                        continue;
                    }
                    // 获取订单详情
                    $orderinfores = $this->getOrderDetails($order_id);
                    if($orderinfores = json_decode($orderinfores,true)) {
                        
                        $order = $orderinfores['result'];
                        $arr['phone'] = $order['buyer_info']['phone'];
                        $items = $order['items'];
                        $arr['title'] = '';
                        $data = [];
                        if($items) {
                            foreach ($items as $key => $value) {
                                preg_match_all('/\#.+\#/', $value['item_name'], $titlearr);
                                if(isset($titlearr[0][0])) {
                                    if(strstr($titlearr[0][0], '会员')) {
                                        $name = '会员';
                                        $id = 0;
                                    } else {
                                        list($name,$id) = explode('_', trim($titlearr[0][0],'#'));
                                    }
                                    
                                } else {
                                    echo json_encode(['status'=>'success']);
                                    return ;
                                }
                                $data[] = [
                                    'num'=>$value['quantity'],
                                    'name'=>isset($name)&&$name?$name:'',
                                    'id'=>isset($id)&&$id?$id:'',
                                ];
                                $arr['title'] = $arr['title'].$value['item_name'].' ';
                            }
                        }
                        $arr['data'] = json_encode($data);
                        $arr['order_id'] = $order_id;
                        $arr['code'] = $this->randomstring();
                        $arr['create_time'] = $arr['update_time'] = time();
                        // var_dump($arr);exit;
                        Db('wdcode')->insert($arr);
                        $this->sendSms($arr['phone'],'SMS_173471929',['pro'=>$arr['title'],'code'=>$arr['code']]);
                    }
                }
            }
        }
	    	
    }

     public function getOrderList($order_type, $add_start, $add_end) {
        return NetUtils::getInstance ()->post ( "https://api.vdian.com/api", array (
                "param" => '{"page_num":' . '1' . ',"page_size":30,"order_type":"' . $order_type . '","add_start":"' . $add_start . '","add_end":"' . $add_end . '"}',
                "public" => $this->buildPublicValue( "vdian.order.list.get" ,'1.2') 
        ) );
    }
    public function buildPublicValue($method, $version = "1.0", $format = "json") {
        return '{"method":"' . $method . '","access_token":"' . $this->getToken() . '","version":"'.$version.'","format":"' . $format . '","lang":"php"}';
    }

    public function getToken()
    {
        $access_token_obj = Db('site')->where(['name'=>'微店access_token'])->find();
        // token没过期
        if($access_token_obj && $access_token_obj['url']>time()) {
            return $access_token_obj['value'];
        }
        $refresh_token_obj = Db('site')->where(['name'=>'微店refresh_token'])->find();
        // https://oauth.open.weidian.com/oauth2/refresh_token?appkey=xxx&grant_type=refresh_token&refresh_token=xxx    
        $res = $this->curl_request("https://oauth.open.weidian.com/oauth2/refresh_token?appkey=690934&grant_type=refresh_token&refresh_token=".$refresh_token_obj['value']);
        if($res = json_decode($res,true)) {
            $access_token = $res['result']['access_token'];
            Db('site')->where(['name'=>'微店access_token'])->update(['value'=>$access_token,'url'=>time()+86000]);
            return $access_token;
        }
    }

    public function getOrderDetails($order_id) {
        return NetUtils::getInstance ()->post ( "https://api.vdian.com/api", array (
                "param" => '{"order_id":"' . $order_id . '"}',
                "public" => $this->buildPublicValue ( "vdian.order.get" ,'1.0') 
        ) );
    }


    /**
     * 发送短信
     * @return stdClass
     */
    public function sendSms($phone='',$tem='SMS_173471929',$arr=[]) {
        // 设置全局客户端
        AlibabaCloud::accessKeyClient('LTAINiJ0Newhjmeb', 'Zgcmohu3eXAUo7Mq5VwRA3h3Jh7fpx')
                    ->regionId('cn-hangzhou')
                    ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                                  ->product('Dysmsapi')
                                  // ->scheme('https') // https | http
                                  ->version('2017-05-25')
                                  ->action('SendSms')
                                  ->method('POST')
                                  ->host('dysmsapi.aliyuncs.com')
                                  ->options([
                                                'query' => [
                                                  'RegionId' => "cn-hangzhou",
                                                  'PhoneNumbers' => $phone,
                                                  'SignName' => "环球人物",
                                                  'TemplateCode' => $tem,
                                                  'TemplateParam' => json_encode($arr),
                                                ],
                                            ])
                                  ->request();
            print_r($result->toArray());
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }

    }

    public function checkcode($code='',$user_id='')
    {
        $user_id = decode($user_id);
        $user = Db('user')->where(['id'=>$user_id])->find();
        // $user = Db('user')->where(['id'=>40427])->find();
        // var_dump($user);exit;
        $codeobj = Db('wdcode')->where(['code'=>$code,'is_use'=>0])->find();
        if($user && $codeobj) {
            $data = json_decode($codeobj['data'],true);
            if($data) {
                $txt = '您已成功兑换 ';
                foreach ($data as $key => $value) {
                    // var_dump($value);exit;
                    // 如果是会员
                    if($value['name']=='会员') {
                        $addtime = 86400*365*$value['num'];
                        $vip_start_time = $user['vip_start_time']?$user['vip_start_time']:time();
                        $vip_end_time = $user['vip_end_time']>time()?($user['vip_end_time']+$addtime):(time()+$addtime);
                        Db('user')->where(['id'=>$user_id])->update(['is_vip'=>1,'vip_end_time'=>$vip_end_time,'vip_start_time'=>$vip_start_time]);
                        $txt = $txt.$value['num'].'年会员 ';
                    } elseif($value['name']=='电子刊') {
                        $this->add_ebookcode($value['num'],$value['id'],$user['id']);
                        $txt = $txt.$value['num'].'份'.$value['name'].' ';
                    } else {
                        $arr['user_id'] = $user['id'];
                        $arr['type'] = $value['name']=='杂志'?2:3;
                        $arr['pid'] = $value['id'];
                        $arr['is_forever'] = $arr['status'] = 1;
                        $arr['create_time'] = time();
                        Db('user_subscribe')->insert($arr);
                        $txt = $txt.$value['num'].'份'.$value['name'].' ';
                    }
                }
                Db('wdcode')->where(['code'=>$code])->update(['is_use'=>1]);
                Db('user')->where(['id'=>$user['id']])->update(['mobile'=>$codeobj['phone']]);
                json_success($txt);
            }
            
        } else {
            json_success('兑换失败');
        }
    }

    public function add_ebookcode($num=1,$eid=0,$uid=0)
    {
        for ($i=0; $i < $num; $i++) { 
            $map = [
                'uid'=>$uid,
                'code'=>$this->getRandomString(10),
                'eid'=>$eid,
                'status'=>1
            ];
            $EbookCode = new \app\api\model\EbookCode();
            $EbookCode->allowField(true)->save($map);
        }
    }

     public function getRandomString($len, $chars=null)  
    {  
        if (is_null($chars)) {  
            $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";  
        }  
        mt_srand(10000000*(double)microtime());  
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {  
            $str .= $chars[mt_rand(0, $lc)];  
        }  
        return $str;  
    } 

    public function curl_request($url){
            $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }
}